from django.views.generic.simple import direct_to_template

from solver import *

def init(request):
	return direct_to_template(request, '1d-cutter/1d_cutting_plan_form.html', {})

	
def cutting_plan_solver(request):
	order_num = request.GET['order_num']
	stock_type = request.GET['stock_type']	
	stock_length = int(request.GET['stock_length'])
	cut_thickness = int(request.GET['cut_thickness'])
	custom_lengths = []
	custom_lengths_str = request.GET['custom_lengths'].replace(',', ' ')	
	for custom_length in custom_lengths_str.split(' '):
		try:			
			custom_length_ext = int(custom_length) + cut_thickness
			if custom_length_ext > stock_length:
				custom_length_ext = stock_length			
			custom_lengths.append(custom_length_ext)
		except ValueError:
			pass
	
	try:
		cutting_plan = get_1d_cutting_plan(stock_length, custom_lengths, cut_thickness)
		return direct_to_template(request, '1d-cutter/1d_cutting_plan_result.html', 
		   {'order_num': order_num,
		    'stock_type': stock_type,
			'cutting_plan': cutting_plan})
	except CalculationError:				
		return direct_to_template(request, '1d-cutter/1d_cutting_plan_error.html', {'error': 'CalculationError'})		
	except Exception, e:		
		return direct_to_template(request, '1d-cutter/1d_cutting_plan_error.html', {'error': e})

